import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, process.cwd())

    return {
        plugins: [vue()],
        resolve: {
            alias: {
                '@': path.resolve(__dirname, './src')
            }
        },
        server: {
            host: true,
            port: 5173,
            open: true,
            proxy: {
                '/api': {
                    target: env.VITE_API_BASE_URL,
                    changeOrigin: true,
                    secure: false,
                    rewrite: (p) => p
                }
            }
        },
        build: {
            outDir: 'dist',
            assetsDir: 'assets',
            sourcemap: false,
            minify: 'esbuild',
            rollupOptions: {
                input: {
                    main: path.resolve(__dirname, 'index.html')
                },
                output: {
                    manualChunks: {
                        'vue-vendor': ['vue', 'vue-router', 'pinia'],
                        'element-plus': ['element-plus', '@element-plus/icons-vue'],
                        'utils': ['marked', 'dompurify']
                    },
                    chunkFileNames: 'js/[name]-[hash].js',
                    entryFileNames: 'js/[name]-[hash].js',
                    assetFileNames: (assetInfo) => {
                        const info = assetInfo.name?.split('.') || []
                        const ext = info[info.length - 1]
                        if (/\.(css)$/.test(assetInfo.name || '')) {
                            return 'css/[name]-[hash].[ext]'
                        }
                        if (/\.(png|jpe?g|svg|gif|tiff|bmp|ico)$/i.test(assetInfo.name || '')) {
                            return 'images/[name]-[hash].[ext]'
                        }
                        return 'assets/[name]-[hash].[ext]'
                    }
                }
            },
            chunkSizeWarningLimit: 1000,
            cssCodeSplit: true,
            target: 'es2015'
        },
        optimizeDeps: {
            include: [
                'vue',
                'vue-router',
                'pinia',
                'element-plus',
                '@element-plus/icons-vue',
                'marked',
                'dompurify'
            ]
        }
    }
})
